<template>
  <div class="vr-upload">
    <el-upload
      ref="uploadRef"
      :action="uploadUrl"
      :show-file-list="false"
      :on-progress="handleProgress"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :multiple="true"
      :accept="accept"
      :http-request="customUpload"
      @change="handleFileChange"
    >
      <el-button size="small" type="primary">
        <slot name="default-text">上传VR图片</slot>
      </el-button>
    </el-upload>

    <!-- 上传进度对话框 -->
    <el-dialog v-model="progressVisible" title="上传进度" width="400px" :close-on-click-modal="false">
      <div class="progress-list" v-loading="uploading" element-loading-text="上传中，请稍等...">
        <div v-for="item in uploadFiles" :key="item.uid" class="progress-item">
          <div class="file-info">
            <span class="filename">{{ item.name }}</span>
            <span class="status">{{ item.status === 'success' ? '上传成功' : item.status === 'error' ? '上传失败' : '上传中' }}</span>
          </div>
          <el-progress 
            :percentage="item.percentage" 
            :status="item.status === 'success' ? 'success' : item.status === 'error' ? 'exception' : ''"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeProgress" :disabled="uploading">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { singleUpload } from '@/utils/upload'

const props = defineProps({
  fileUrl: {
    type: String,
    default: ''
  },
  accept: {
    type: String,
    default: '.jpg,.jpeg,.png'
  }
})

const emit = defineEmits(['update:fileUrl'])

// 上传相关变量
const uploadUrl = ref(process.env.NODE_ENV === 'development' 
  ? process.env.VUE_APP_SERVICE_BASE + '/file/sysFile/uploadList'
  : window.location.origin + '/file/sysFile/uploadList'
)

const uploadRef = ref()
const uploadFiles = ref([])
const progressVisible = ref(false)
const uploading = ref(false)

// 跟踪已选择的文件数量
const selectedFilesCount = ref(0)

// 使用一个标志来跟踪是否需要上传
let uploadTimer = null

// 上传前检查
const beforeUpload = (file) => {
  // 检查文件类型
  const isValidType = props.accept.split(',').some(type => 
    file.name.toLowerCase().endsWith(type.toLowerCase())
  )
  
  if (!isValidType) {
    ElMessage.error('只能上传jpg/jpeg/png格式的图片!')
    return false
  }

  // 检查文件大小 (限制为100MB)
  const isLt20M = file.size / 1024 / 1024 < 100
  if (!isLt20M) {
    ElMessage.error('图片大小不能超过20MB!')
    return false
  }

  return true
}

// 自定义上传
const customUpload = async (options) => {
  const { file } = options
  
  // 添加到上传列表，但不立即上传
  const fileInfo = {
    uid: file.uid,
    name: file.name,
    percentage: 0,
    status: 'waiting',
    raw: file  // 保存原始文件对象
  }
  uploadFiles.value.push(fileInfo)
  progressVisible.value = true
  
  // 清除之前的定时器
  if (uploadTimer) {
    clearTimeout(uploadTimer)
  }
  
  // 设置一个短暂的延迟，等待所有文件都被添加到列表
  uploadTimer = setTimeout(async () => {
    await uploadAllFiles()
  }, 100)
}

// 监听文件选择事件
const handleFileChange = (files) => {
  selectedFilesCount.value = files.length
}

// 批量上传所有文件
const uploadAllFiles = async () => {
  if (!uploadFiles.value.length) return
  
  uploading.value = true
  try {
    const formData = new FormData()
    
    // 将所有文件添加到 fileList 参数
    uploadFiles.value.forEach(file => {
      formData.append('fileList', file.raw)
    })
    // 发起单次上传请求
    const res = await singleUpload(
      formData,
      uploadUrl.value,
      (progress) => {
        // 更新所有文件的进度
        uploadFiles.value.forEach(file => {
          file.percentage = progress.percent
          file.status = 'uploading'
        })
      }
    )

    // 处理成功响应
    uploadFiles.value.forEach(file => {
      file.status = 'success'
      // // 假设后端返回的是文件URL数组，需要按顺序匹配
      // const fileResult = res.data.find(item => item.originalName === file.name)
      // if (fileResult) {
      //   file.url = fileResult.url
      // }
    })

    // 触发成功回调
    // if (res.data.url.includes('10.10.0.19:19000')) {
    //   res.data.url = res.data.url.replace('10.10.0.19:19000', 'oss.w25.foxtest.net:10000')
    // }
    emit('update:fileUrl', res.data.url)
    
  } catch (error) {
    // 处理错误 - 将所有文件标记为失败
    uploadFiles.value.forEach(file => {
      file.status = 'error'
    })
    ElMessage.error('文件上传失败')
  } finally {
    uploading.value = false
  }
}

// 关闭进度弹窗
const closeProgress = () => {
  if(!uploading.value) {
    progressVisible.value = false
    uploadFiles.value = []
  }
}

</script>

<style lang="scss" scoped>
.vr-upload {
  display: inline-block;
}

.progress-list {
  max-height: 300px;
  overflow-y: auto;
  
  .progress-item {
    padding: 10px 0;
    
    .file-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      
      .filename {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 10px;
      }
      
      .status {
        font-size: 12px;
        &.success {
          color: #67c23a;
        }
        &.error {
          color: #f56c6c;
        }
      }
    }
  }
}
</style>